package blt.app_core.api.other;


import java.io.File;
import java.util.List;

import blt.app_core.api.base.LoginInterceptor;
import blt.app_core.api.base.bean.OAuth;
import blt.app_core.api.base.bean.State;
import blt.app_core.api.base.callback.ComBack;
import blt.app_core.api.base.callback.StateCallback;
import blt.app_core.api.impl.BaseImpl;
import blt.app_core.api.login.bean.User;
import blt.app_core.api.message.bean.BannerInfo;
import blt.app_core.api.other.bean.FeedBackVo;
import blt.app_core.log.Logger;
import blt.app_core.utils.CacheUtil;
import blt.app_core.utils.UriProdiver;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.GsonConverterFactory;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by xgp on 2017/6/20.
 */

public class OutImpl extends BaseImpl<OutService> implements OutApi {

    @Override
    public void getBanner() {
        mService.getBanner().enqueue(new Callback<OAuth<BannerInfo>>() {

            @Override
            public void onResponse(Call<OAuth<BannerInfo>> call, Response<OAuth<BannerInfo>> response) {
                if (response.body().errcode == 200) {
                    List<BannerInfo> bannerInfos = response.body().data;
                    notifyClients(OutApi.class, OutApi.onBanner, bannerInfos);
                }
            }

            @Override
            public void onFailure(Call<OAuth<BannerInfo>> call, Throwable t) {

            }
        });

    }

    @Override
    public void uploadFile(String url) {
//        builderLoginRequest();

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        LoginInterceptor in = new LoginInterceptor(CacheUtil.getCache().getUid(),
                CacheUtil.getCache().getCookie());

        // 配置 client
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).addInterceptor(in)
                .build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl(UriProdiver.BASE_URL).client(client)
                .addConverterFactory(GsonConverterFactory.create()).build();

        OutService outService = retrofit.create(OutService.class);

        File file = new File(url);
        if (!file.exists()) {
            Logger.d("file is not exists");
            return;
        }
        final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

        Call<State<String>> call = outService.upload(null, body);
        call.enqueue(new StateCallback<String>() {
            @Override
            protected void onSuccess(String picName) {
                Logger.d("uploadFile:" + picName);
                notifyClients(OutApi.class, OutApi.onUpload, picName);
            }
        });
//        call.enqueue(new Callback<OAuth<String>>() {
//            @Override
//            public void onResponse(Call<OAuth<String>> call, Response<OAuth<String>> response) {
//                Logger.d("uploadFile"+response.body().toString());
//
//            }
//
//            @Override
//            public void onFailure(Call<OAuth<String>> call, Throwable t) {
//                notifyClients(OutApi.class, OutApi.onUpload);
//            }
//        });

//        File file = new File(url);
//        // 创建 RequestBody，用于封装构建RequestBody
//        RequestBody requestFile =
//                RequestBody.create(MediaType.parse("multipart/form-data"), file);
//
//        // MultipartBody.Part  和后端约定好Key，这里的partName是用image
//        MultipartBody.Part body =
//                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
//
//        // 添加描述
////        String descriptionString = "hello, 这是文件描述";
////        RequestBody description =
////                RequestBody.create(
////                        MediaType.parse("multipart/form-data"), descriptionString);
//
//        // 执行请求
//        Call<OAuth> call = mService.upload(null, body);
//        call.enqueue(new Callback<OAuth>() {
//            @Override
//            public void onResponse(Call<OAuth> call,
//                                   Response<OAuth> response) {
//                Logger.d(response.message() + "/" + response.errorBody());
//                if (!response.isSuccessful()) {
//                    return;
//                }
//                Logger.v("Upload", "success" + response.body());
//            }
//
//            @Override
//            public void onFailure(Call<OAuth> call, Throwable t) {
//                Logger.e("Upload error:", t.getMessage());
//            }
//        });
    }

    @Override
    public void uploadIcon(String url) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        LoginInterceptor in = new LoginInterceptor(CacheUtil.getCache().getUid(),
                CacheUtil.getCache().getCookie());

        // 配置 client
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).addInterceptor(in)
                .build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl(UriProdiver.BASE_URL).client(client)
                .addConverterFactory(GsonConverterFactory.create()).build();

        OutService outService = retrofit.create(OutService.class);

        File file = new File(url);
        if (!file.exists()) {
            Logger.d("file is not exists");
            return;
        }
        final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

        Call<State<User>> call = outService.uploadIcon(body);
        call.enqueue(new StateCallback<User>() {
            @Override
            protected void onSuccess(User user) {
//                Logger.d("uploadFile:" + user.icon);
                notifyClients(OutApi.class, OutApi.onUploadIcon, user.icon);
            }
        });
    }

    @Override
    public void registPush(String deviceToken) {
        builderLoginRequest();
        mService.registPush(deviceToken).enqueue(new Callback<State>() {
            @Override
            public void onResponse(Call<State> call, Response<State> response) {
            }

            @Override
            public void onFailure(Call<State> call, Throwable t) {

            }
        });
    }

    @Override
    public void saveOpinion(String feedbackType, String issue) {
        mService.submitOpinion(feedbackType, issue).enqueue(new Callback<State>() {
            @Override
            public void onResponse(Call<State> call, Response<State> response) {
//               notifyClients(OutApi.class,OutApi.onSubmitOp);
            }

            @Override
            public void onFailure(Call<State> call, Throwable t) {

            }
        });
    }

    @Override
    public void getOpinionType() {
        String type = "feedback_type";

        mService.getType(type).enqueue(new ComBack<FeedBackVo>() {
            @Override
            protected void onSuccess(List<FeedBackVo> data) {
                notifyClients(OutApi.class, OutApi.onOpinionType, data);
            }
        });
    }

    @Override
    public void getFeedbackList(int page, int size) {
        mService.getFeedbackList(page, size).enqueue(new ComBack<FeedBackVo>() {
            @Override
            protected void onSuccess(List<FeedBackVo> data) {
                notifyClients(OutApi.class, OutApi.onFeedbackList, data);
            }
        });

    }

    @Override
    public void getFeedBackDetail(int id) {
        mService.getFeedbackDetail(id).enqueue(new Callback<State>() {
            @Override
            public void onResponse(Call<State> call, Response<State> response) {

            }

            @Override
            public void onFailure(Call<State> call, Throwable t) {

            }
        });
    }

}
